<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        center
        show-icon
        title="添加商品信息"
        type="info"
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        align-center
        :active="+activeIndex"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs栏 -->
      <!-- from表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="Cateprops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="onSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 浏览图片 -->
    <el-dialog title="图片浏览" :visible.sync="dialogVisibleImg" width="50%">
      <img :src="previewPath" alt="" style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // tabs对应索引
      activeIndex: 0,
      //   添加表单数据
      addForm: {
        goods_name: '', //名称
        goods_price: 0, //价格
        goods_weight: 0, //重量
        goods_number: 0, //数量
        goods_cat: [], //分类列表
        pics: [], //上传的图片临时路径
        goods_introduce: '', //商品介绍
        attrs: [] //商品的参数
      },
      // 表单验证
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择对应列表', trigger: 'blur' }
        ]
      },
      //   商品分类数据列表
      cateList: [],
      Cateprops: {
        expandTrigger: 'hover',
        label: 'cat_name', //看中
        value: 'cat_id', //选中
        children: 'children'
      },
      // 动态参数列表
      manyTableData: [],
      // 静态参数列表
      onlyTableData: [],
      // 上传图片地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 给上传图片添加一个请求头
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      // 浏览图片地址
      previewPath: '',
      // 控制浏览图片对话框
      dialogVisibleImg: false
    }
  },
  created() {
    this.getcateList()
  },
  methods: {
    //   获取所有商品分类数据
    async getcateList() {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.errot('获取失败')
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 级联选择器选中会触发
    handleChange() {
      console.log(this.addForm.goods_cat)
      //   控制级联只能选中三级
      if (this.addForm.goods_cat.length !== 3)
        return (this.addForm.goods_cat = [])
    },
    // 切换标签的钩子，如果为false阻止切换
    beforeLeave(activeName, oldActiveName) {
      // console.log('离开标签页名字' + oldActiveName)
      // console.log('即将标签页名字' + activeName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 选择tabs栏触发
    async tabClick() {
      // console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        // 动态参数列表
        const { data: res } = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200) return this.$message.errot('获取失败')
        //  把attr_vals转换为数组
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })

        this.manyTableData = res.data
        console.log(this.manyTableData)
      }
      // 静态参数
      if (this.activeIndex === '2') {
        // 动态参数列表
        const { data: res } = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) return this.$message.errot('获取失败')

        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 图片预览触发
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.dialogVisibleImg = true
    },
    // 点击删除触发
    handleRemove(file) {
      // console.log(file)
      // 获取要删除的图片路径
      const filePath = file.response.data.tmp_path
      // 拿到对应的索引
      const i = this.addForm.pics.findIndex(item => item.pic == filePath)
      // console.log(i)
      this.addForm.pics.splice(i, 1)
      // console.log(this.addForm)
    },
    // 图片上传成功的钩子
    onSuccess(response) {
      // console.log(response)
      // 拼接图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // push到pic
      this.addForm.pics.push(picInfo)
      // console.log(this.addForm.pics)
    },
    // 添加商品
    add() {
      // console.log(this.addForm)
      this.$refs.addFormRef.validate(async val => {
        if (!val) return this.$message.error('请填写必要表单项')
        // 先深拷贝一份
        // lodash cloneDeep(obj)
        const from = _.cloneDeep(this.addForm)
        from.goods_cat = from.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态参数
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        // console.log(this.addForm.attrs)
        from.attrs = this.addForm.attrs

        console.log(from)
        const { data: res } = await this.$axios.post('goods', from)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 分类id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important ;
}

.btnAdd {
  margin-top: 15px;
}
</style>
